package com.example.assignment4.service;


import com.example.assignment4.exception.CustomException;
import com.example.assignment4.commodity;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class commoditySerIm implements commodityService {

    private Map<Long, commodity> commodities= Collections.synchronizedMap(new HashMap<Long, commodity>());

    @Override
    public void add(commodity commodity) {
        Long id=commodity.getId();
        if(commodities.containsKey(id)){
            throw new CustomException("id重复");
        }
        commodities.put(id,commodity);
    }

    @Override
    public void deleteById(Long id) {
        if(!commodities.containsKey(id)){
            throw new CustomException("id不存在");
        }
        commodities.remove(id);
    }

    @Override
    public void updateById(commodity commodity) {
        Long id=commodity.getId();
        if(!commodities.containsKey(id)){
            throw new CustomException("id不存在");
        }
        commodities.put(id,commodity);
    }

    @Override
    public commodity getById(Long id) {
        if(commodities.containsKey(id)){
            return commodities.get(id);
        }
        return null;
    }

    @Override
    public List<commodity> getAll() {
        List<commodity> commodityList=new ArrayList<commodity>();
        for(Long id : commodities.keySet()){
            commodityList.add(commodities.get(id));
        }
        return commodityList;
    }
}
